package com.xingfly.product.product;

import com.xingfly.jpa.common.BaseEntity;
import com.xingfly.product.sdk.event.product.ProductCreatedEvent;
import com.xingfly.product.sdk.event.product.ProductNameUpdatedEvent;
import lombok.*;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.Table;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 产品
 * Created by SuperS on 2019/11/8.
 *
 * @author SuperS
 */
@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "t_product")
@EqualsAndHashCode(callSuper = true)
@EntityListeners(AuditingEntityListener.class)
public class Product extends BaseEntity<ProductId> {

    private String name;

    private String description;

    private BigDecimal price;

    private Integer inventory;

    private String categoryId;

    private Boolean deleted;

    public static Product create(String name, String description, BigDecimal price, String categoryId) {
        Product p = Product.builder()
                .name(name)
                .description(description)
                .price(price)
                .inventory(0)
                .deleted(false)
                .categoryId(categoryId)
                .build();
        p.setId(new ProductId());
        p.setCreateTime(LocalDateTime.now());
        ProductCreatedEvent event = new ProductCreatedEvent(p.getId().getId(), name, description, price, p.getCreateTime());
        p.registerEvent(event);
        return p;
    }

    public void updateName(String newName) {
        registerEvent(new ProductNameUpdatedEvent(this.getId().getId(), name, newName));
        this.name = newName;
    }

    public void updateInventory(int inventory) {
        this.inventory = inventory;
    }
}
